/**
 * Created by leiqr on 2015/6/8.
 * 运营中心首页
 */

define(function (require, exports, module) {
    var $ = require("jquery");
    var template = require("template");
    var device = require('js/detectDevice').deviceInfo;
    require('jquerycookie');
    require('js/topNotice');
    require('jqueryAppear');
    require('jquerySuperslide');
    require('js/toTop');
    //require('jqueryBizQQ');
    //var weixinShare = require('/plugins/weixin/weixinshare');
    var dialogModule = require('js/goToLogin');
    var api_prefix = api_domain + "/api/index.php?r=cms/"; //api前缀
    var jsopName = "jsonp_data";
    var guide_tips_cookie_name = 'guide_tips';//cookie 记录
    var showGuideTips = !$.cookie(guide_tips_cookie_name) && !device.os.phone && !device.os.tablet;
    showGuideTips = false;

    var main = {
        init: function () {
            var self = this,
                defer = this.requestData();
            template.helper('encodeURL', function (str) {
                return encodeURIComponent(str);
            });
            defer.then(function (res) {
                if(!res){
                    dialogModule.dialog.showModal();
                    return;
                }
                self.bindEvt();
                self.fillData(res)
                self.animationOnScroll();
                self.fullSlide();
                if (showGuideTips) {
                    setTimeout(function () {
                        self.showTipLevel_1(true);
                        self.bindTipEvents();
                    }, 2500)
                }
              
                var isEmpty = function(obj) {
                    if(typeof(obj) === 'undefined'){
                        return true;
                    }
                    for(var i in obj) {
                        if(obj.hasOwnProperty(i)) {
                            return false;
                        }
                    }
                    return true;
                }
                if(isEmpty(res.download) && isEmpty(res.college) && isEmpty(res.redmine_log)) {
                    $('#recommendDiv').parent().removeClass();
                    $('.hd').css({'right': '14%', 'text-align': 'center'});
                    $('.fullSlide').css('left', '16%');
                }
            });
            //$.BizQQ([{selector: 'js_BizQQWPA'},{selector: 'BizQQWPABC'}]);
            //weixinShare.initShare({
            //    title:document.title,
            //    desc:'☞点击这里，秘笈在此，从此当个会玩的城里人！',
            //    link:location.href,
            //    imgUrl:$('img').eq(0).attr('src')
            //})
        },
        bindEvt: function () {
            //初次进入指引
            var self = this;
            //导航条跳转链接地址
            $('#navbar').click(function(e){
                var target = $(e.target);

                var aid = target.data('aid') || target.parent().data('aid');

                if (aid !== undefined) {
                    var pid = target.data('pid') || target.parent().data('pid');
                    location.href = "list.html?dirId=" + aid + "&pid=" + pid;
                }
            });
            //下载
            $("#downloadDiv").on('click', '.download', function (evt) {
                evt.preventDefault();
                evt.stopPropagation();
                var fileurl = $(evt.target).data('fileurl');
                window.location.href = fileurl;
            });
            $("#collegeDiv").on('click', '.download', function (evt) {
                evt.preventDefault();
                evt.stopPropagation();
                var fileurl = $(evt.target).data('fileurl');
                window.location.href = fileurl;
            });
        },
        bindTipEvents: function (){
            var guideTip = $('#guideTip');
            var tips = guideTip.find('.tip_btn');
            var self = this;
            guideTip.click(function (e){
                var target = $(e.target);
                
                if(target.hasClass('tip_btn') || target.parent().hasClass('tip_btn')) {
                    var index = target.attr('rel');
                    if (!index) {
                        target = target.parent();
                        index = target.attr('rel');
                    }
                    
                    if (index == 1) {
                        target.parent().hide();
                        self.showTipLevel_2(true);
                    } else {
                        if (index == tips.length) {
                            $(this).fadeOut();
                            disabledMouseWheel(true);
                        } else {
                            target.parent().hide();
                            $(tips[index]).parent().show();
                        }   
                    }
                           
                    if ($('.TipMsg' + (index - 1)).length) {
                        $('.TipMsgCopy' + (index - 1)).remove();
                    }
                    var tipMsgs = $('.TipMsg' + index);
                    if (tipMsgs.length) {
                        for (var i = 0; i < tipMsgs.length; i++) {
                            var tipMsg = $(tipMsgs[i]);
                            var offset = tipMsg.offset();
                            $('body').append(tipMsg.clone().removeClass('TipMsg').addClass('tipTarget TipMsgCopy' + index).css({
                                top: offset.top,
                                left: offset.left
                            }));                                     
                        }      
                        
                        window.scrollTo(0,$('.TipMsgCopy' + index).offset().top - $(tips[index]).parent().find('img').offset().top + $('body').scrollTop());           
                    }   
                    return;  
                }
                
                if (target.hasClass('tip_close') || target.parent().hasClass('tip_close')) {   
                    if (!target.hasClass('tip_close')) {
                        target = target.parent();
                    }         
                    target.parent().hide();
                    $(this).fadeOut();
                    disabledMouseWheel(true);
                    var index = target.next().attr('rel');
                    if ($('.TipMsg' + (index - 1)).length) {
                        $('.TipMsgCopy' + (index - 1)).remove();
                    }
                }
            });
        },
        /**
         * 新手指引第一个遮罩层显示隐藏控制
         * @param show  Bool
         */
        showTipLevel_1: function (show) {
            var tipMaskBg = $('.tipMaskBg');
            if (show) {
                tipMaskBg.show();
                $('.tipLevel_1', tipMaskBg).fadeIn(300);
            } else {
                $('.tipLevel_1', tipMaskBg).fadeOut(300);
            }
            disabledMouseWheel(false)
        },
        /**
         * 新手指引第二个遮罩层显示隐藏控制
         * @param show  Bool
         */
        showTipLevel_2: function (show) {
            var tipMaskBg = $('.tipMaskBg'), self = this;
            if (show) {
                $('.tipLevel_2', tipMaskBg).fadeIn(300);
                setTimeout(function () {
                    $('#joyRideTipContent').joyride({
                        cookieMonster: true,
                        posOffset: 26,
                        startTimerOnClick: false,
                        cookieName: guide_tips_cookie_name,
                        nextButton: false,
                        timer: 2000,
                        postStepCallback: function (index) {
                            // if (index == -1) {
                            //     $(".level2_btn").fadeIn(300);
                            // }
                        },
                        showStepCallback: function (index, curTip) {
                            // if ($(".tipTarget" + (index + 1)).length < 1 && index !== -1) {
                            //     var TipMsg_i = $("#TipMsg" + (index + 1));
                            //     var offset = TipMsg_i.offset();
                            //     var title = TipMsg_i.html();
                            //     if (index == 6) {
                            //         $('.tipMaskBg').click(function () {
                            //             self.showTipLevel_2(false);
                            //         });
                            //         title = "戳这里直达帮助中心哦~"
                            //     }
                            //     $("body").append("<div class='font_size20 title_line text-left tipTarget tipTarget" + (index + 1) + "'>" + title + "</div>");
                            //     $(".tipTarget" + (index + 1)).css({top: offset.top, left: offset.left});
                            // }
                        }
                    });
                }, 400);
            } else {
                tipMaskBg.fadeOut(300);
                $('.joyride-tip-guide').fadeOut();
                $('.tipTarget').fadeOut();
                $('.tipLevel_2', tipMaskBg).fadeOut(300);
            }
        },
        requestData: function () {
            var self = this;
            var url = api_prefix + "cms-data/get-index&jsonp=" + jsopName;
            var defer = $.Deferred();
            $.getScript(url, function () {
                defer.resolve(window[jsopName]);
            });
            return defer.promise();
        },
        /**
         * 填充各模块数据
         * @param   res Obj
         */
        fillData: function (res) {
            template.helper('formatStringLen', this.formatStringLen);
            this.fillBanner(res.home_banner);
            this.fillNotice(res.notice);
            this.fillDownload(res.download);
            this.fillCollege(res.college);
            this.fillRecommed(res.recommend);
            this.fillStudy(res.study);
            this.fillProduct(res.product);
        },
        fillProduct: function (data) {
            var productData = data;
            if (productData && productData.children && productData.children.length > 0) {
                var html = template('product', productData);
                $("#productDiv").html(html);
            }
        },
        fillStudy: function (data) {
            var studyData = data;
            if (studyData && studyData.children && studyData.children.length > 0) {
                var html = template('study', studyData);
                $("#studyDiv").html(html);
            }
        },
        fillRecommed: function (data) {
            var recommendData = data;
            if (recommendData && recommendData.children && recommendData.children.length > 0) {
                var html = template('recommend', recommendData);
                $("#recommendDiv").html(html);
            }
        },
        fillCollege: function (data) {
            var collegeData = data;
            if (collegeData && collegeData.list && collegeData.list.length > 0) {
                var html = template('college', collegeData);
                $("#collegeDiv").html(html);
            }
        },
        fillNotice: function (data) {
            var noticeData = data;
            if (noticeData && noticeData.list && noticeData.list.length > 0) {
                var html = template('notice', noticeData);
                $("#noticeDiv").html(html);
            }
        },
        fillDownload: function (data) {
            var downloadData = data;
            if (downloadData && downloadData.list && downloadData.list.length > 0) {
                var html = template('download', downloadData);
                $("#downloadDiv").html(html);

            }
        },
        fillBanner: function (data) {
            var bannerData = data;
            if (bannerData && bannerData.list && bannerData.list.length > 0) {
                var html = template('banner', bannerData);
                $("#bannerDiv").html(html);
                if (bannerData.list.length == 1) {
                    $("#bannerDiv .hd").hide()
                }
            }
        },
        formatStringLen: function (str, len) {
            var strlen = 12;
            if (typeof len == 'number') {
                strlen = len;
            }
            if (typeof  str == 'string') {
                if (str.length > strlen) {
                    return str.substring(0, strlen) + '...';
                } else {
                    return str;
                }
            }
            return '';
        },
        animationOnScroll: function () {
            $('.animated').appear(function () {
                var elem = $(this);
                var animation = elem.data('animation');
                if (!elem.hasClass('visible')) {
                    var animationDelay = elem.data('animation-delay');
                    if (animationDelay) {
                        setTimeout(function () {
                            elem.addClass(animation + " visible");
                        }, animationDelay);
                    } else {
                        elem.addClass(animation + " visible");
                    }
                }
            });
        },
        fullSlide: function () {
            $(".fullSlide").hover(function () {
                $(this).find(".prev,.next").stop(true, true).fadeIn()
            }, function () {
                $(this).find(".prev,.next").fadeOut()
            });
            $(".fullSlide").slide({
                titCell: ".hd",
                mainCell: ".bd",
                effect: "fade",
                autoPlay: true,
                autoPage: true,
                trigger: "click",
                startFun: function (i) {
                    var curLi = $(".fullSlide .bd li").eq(i);
                    if (!!curLi.attr("_src")) {
                        curLi.css("background-image", curLi.attr("_src")).removeAttr("_src")
                    }
                }
            });
        },
        signout: function(){
            var self = this;
            var url = api_prefix + "site/logout&jsonp=" + jsopName;
            var defer = $.Deferred();
            $.getScript(url, function () {
                defer.resolve(window[jsopName]);
            });
            return defer.promise();
        }
    };

    function disabledMouseWheel(enable) {
        if (!enable) {
            if (document.addEventListener) {
                document.addEventListener('DOMMouseScroll', scrollFunc, false);
            }//W3C
            window.onmousewheel = document.onmousewheel = scrollFunc;//IE/Opera/Chrome

        } else {
            if (document.removeEventListener) {
                document.removeEventListener('DOMMouseScroll', scrollFunc, false);
            }//W3C
            window.onmousewheel = document.onmousewheel = function () {
            };//IE/Opera/Chrome


        }

    }

    function scrollFunc(evt) {
        evt = evt || window.event;
        if (evt.preventDefault) {
            // Firefox
            evt.preventDefault();
            evt.stopPropagation();
        } else {
            // IE
            evt.cancelBubble = true;
            evt.returnValue = false;
        }
        return false;
    }

    //根据是否需要首次指引来加载相关文件
    if (showGuideTips) {
        var cssurl = '../css/joyride-2.0.1.css';
        cssurl = '<link rel="stylesheet" href="' + cssurl + '" />';
        $('head').prepend(cssurl);
        var tipsContent = '<ol id="joyRideTipContent">' +
            '<li data-id="TipMsg1" data-class="so-awesome" data-options="tipLocation:top;tipAnimation:fade" data-text="Next" class="custom">' +
            '<p>浩瀚的宝库资料不着急，先来看看时下最热的干货推荐！</p>' +
            '</li>' +
            '<li data-id="TipMsg2" data-button="Next" data-options="tipLocation:top;tipAnimation:fade">' +
            '<p>最权威的教授，最专业的课程，让你从此玩转云客！</p>' +
            '</li>' +
            '<li data-id="TipMsg3" data-button="Next" data-options="tipLocation:top;tipAnimation:fade">' +
            '<p> 炫酷的产品，强大的功能不知道怎么整？别着急，这里看看哦。</p>' +
            '</li>' +
            '<li data-id="TipMsg4" data-button="Next" data-options="tipAnimation:fade">' +
            '<p> 专业的地产行业内专题报告，Internet+大时代，纵横辟阖少不了行业大视角！</p>' +
            '</li>' +
            '<li data-id="TipMsg5" data-button="Next" data-options="tipAnimation:fade">' +
            '<p> duang~吐血整理的大量干货，无论你是新手还是高手，总有你想要的在这里！</p>' +
            '</li>' +
            '<li data-id="TipMsg6" data-button="Next" data-options="tipLocation:bottom;tipAnimation:fade">' +
            '<p> 重要消息不再漏，通知、公告都会把产品最新功能及时推送！</p>' +
            '</li>' +
            '<li data-id="TipMsg7" data-button="Next" data-options="tipLocation:bottom;tipAnimation:fade">' +
            '<p>帮助中心，你值得拥有。</p>' +
            '</li>' +
            '</ol>'
        $('body').append('<ol id="joyRideTipContent"></ol>');
        require.async('jqueryJoyride', function () {
            main.init();
        });
    } else {
        main.init();
    }
});







